#include "Timer.h"
#include "Nixie.h"
#include "KeyBoard.h"
#include "AT24C02.h"
#include "LCD1602.h"
#include "DelayTime.h"

// 通过定时器不断扫描数码管和键盘
unsigned char key_n;
unsigned char min,sec,mini_sec;
unsigned char RunFlag = 0;

void main()
{
	TimerInit();
//	LCD_Init();
	
	while(1)
	{
		key_n = Key_Num();
		if(key_n == 1) // 启动、关闭计时
		{
			RunFlag = !RunFlag;
		}
		else if(key_n == 2) // 清空计时
		{

			min = sec = mini_sec = 0;
		}
		else if(key_n == 3)
		{

			// 存储
			AT24C02_WriteByte(0,min);
			Delayxms(5);
			AT24C02_WriteByte(1,sec);
			Delayxms(5);
			AT24C02_WriteByte(2,mini_sec);
			Delayxms(5);
		}
		else if(key_n == 4)
		{

			// 读取
			min = AT24C02_ReadByte(0);
			sec = AT24C02_ReadByte(1);
			mini_sec = AT24C02_ReadByte(2);
		}
		
		Set_Buf(1,min / 10);
		Set_Buf(2,min % 10);
		Set_Buf(3,11);
		Set_Buf(4,sec / 10);
		Set_Buf(5,sec % 10);
		Set_Buf(6,11);
		Set_Buf(7,mini_sec / 10);
		Set_Buf(8,mini_sec / 10);

			//min,sec,mini_sec;
//			LCD_ShowNum(1,1,min,2);
//			LCD_ShowNum(1,4,sec,2);
//			LCD_ShowNum(1,7,mini_sec,3);
			
	}
}
void Sec_Loop()
{
	if(RunFlag)
	{
		mini_sec++;
		if(mini_sec >= 100)
		{
			sec++;
			mini_sec = 0;
			if(sec >= 60)
			{
				sec = 0;
				min++;
				if(min >= 60)
				{
					min = 0;
				}
			}
		
		}
	}
}


// 定时器的中断函数，调用自定义函数时，需要小心
// 自定义函数中不可有Delay，或 加起来的所有延时时间，必须小于下次进入中断的时间
// 不然该中断还未结束，又继续执行
void Timer0_Routine()		interrupt 1
{
	static int count_key ,count_nix,count_t; 
	TL0 = 0x18;		
	TH0 = 0xFC;	

	count_key++;
	// 扫描按键
	if(count_key >= 20)
	{
		count_key = 0;
		Key_Loop();
	}	

	count_nix++;
	// 扫描数码管
	if(count_nix >= 2)
	{
		count_nix = 0;
		Nixie_Loop();
	}

	count_t++;
	// 每隔10ms  mini_sec 计数
	if(count_t >= 10)
	{
		count_t = 0;
		Sec_Loop();
	}
}